package cron

import (
	"time"

	"github.com/astaxie/beego"
	"publish/app/account/model"
	model2 "publish/model"
	"runtime/debug"
	"publish/pub-lib/baijia"
	"net/url"
	"github.com/astaxie/beego/httplib"
	"errors"
	"encoding/json"
)

var (
	PraseRemoteAddr = beego.AppConfig.String("prase_api")
)

func PraseArticle(articleUrl string) (*baijia.FeedArticle,error){
	api := PraseRemoteAddr + `/article/feed?url=`+url.QueryEscape(articleUrl)
	feedArticle := baijia.FeedArticle{}
	if err := httplib.Get(api).ToJSON(&feedArticle); err != nil {
		return nil,err
	}

	if len(feedArticle.Title) == 0 || len(feedArticle.Feed) == 0{
		return nil,errors.New("解析内容为空："+api)
	}

	return &feedArticle,nil
}


type AutoTaskWorker struct {}

func (w *AutoTaskWorker) run() {
	defer func() {
		if r := recover(); r != nil {
			debug.PrintStack()
			beego.Error("[recover]", r)
		}
	}()


	for {
		autoTask, err := model.GetNeedPubAutoTask()
		if err != nil {
			time.Sleep(time.Second * 10)
			continue
		}

		account,err := model.GetAccountById(autoTask.AccountId)
		if err != nil{
			beego.Error("没有发现账号")
			autoTask.Status = 3
			if err = model.UpdateAutoTask(&autoTask);err != nil{
				beego.Error(err)
			}
			continue
		}

		for count := autoTask.LessCount;count > 0;count--{
			article,err := model.GetArticle(autoTask.ArticleCat)
			if err != nil{
				autoTask.Status = 0
				autoTask.LessCount = count
				if err = model.UpdateAutoTask(&autoTask);err != nil{
					beego.Error(err)
				}
				break
			}
			if err = Publish(account,autoTask.PubCat,article);err != nil{
				autoTask.Status = 0
				autoTask.LessCount = count
				if err = model.UpdateAutoTask(&autoTask);err != nil{
					beego.Error(err)
				}
				break
			}

			if count == 1{
				autoTask.Status = 2
				autoTask.EndTime = time.Now()
			}
			autoTask.LessCount = 0
			if err = model.UpdateAutoTask(&autoTask);err != nil{
				beego.Error(err)
			}
		}
	}
}

func Publish(account *model.Account,cat string,article model.Article) error{
	if len([]rune(article.Title)) < 5 || len([]rune(article.Title)) > 30{
		return errors.New("标题不符合规则")
	}

	articleFeed,err := PraseArticle(article.Url)
	if err != nil{
		beego.Error(err)
		return err
	}

	articleBytes,err := json.Marshal(articleFeed)
	if err != nil{
		beego.Error(err)
		return err
	}

	pub := model2.PubTask{
		AccountId: account.Id,
		ArticleCat: cat,
		Article:    string(articleBytes),
		Tag:        "",
		Type:       "ARTICLE",
		Status:     model2.Pub_Status_Nopub,
	}

	_, err = model2.InsertPubTask(pub)
	if err != nil {
		beego.Error(err)
		return err
	}
	beego.Info("平台:",account.Plat,"账号:",account.NickName,"自动插入发布：",article.Title)
	return nil
}

func StartAutoTaskWorker() {
	work := &AutoTaskWorker{}
	count :=  beego.AppConfig.DefaultInt("auto_worker_count",3)
	for i:= 0;i < count;i++{
		go work.run()
	}
}


